package com.bnz.servlet;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import com.bnz.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {

    private StudentService studentService;

    @Override
    public void init() throws ServletException {
        studentService =new StudentServiceImpl();
    }

    /**
     * 2. 根据请求参数cmd进行路由分发
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=utf8");
        //1. 得到请求参数
        String cmd = req.getParameter("cmd");
        //2. 根据参数调用不同的方法
        if(StrUtil.isNotBlank(cmd)){
            if("list".equals(cmd)){
                list(req,resp);
            }else if("findByPage".equals(cmd)){
                findByPage(req,resp);
            }
        }
    }

    private void findByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{




        //4.1 得到查询的分页参数
        int page = new Integer(req.getParameter("page"));
        int pagesize = new Integer(req.getParameter("pagesize"));
        //4.2 开始分页查询
        PageResult<Student> pr = studentService.findByPage(page,pagesize);
        //4.3 将上面的学生集合转换为json串
        String s = JSON.toJSONString(pr);
        //4.4 输出内容到页面
        resp.getWriter().println(s);
        //4.5 刷新页面
        resp.getWriter().flush();



    }


    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //3.0 指定响应页面的格式及字符休编码
        //3.1 查询所有学生列表
        List<Student> students = studentService.findAll();
        //3.2 将上面的学生集合转换为json串
        String s = JSON.toJSONString(students);
        //3.3 输出内容到页面

        resp.getWriter().println(s);
        //3.4 刷新页面
        resp.getWriter().flush();
    }


}
